package cn.smbms.controller;

import cn.smbms.pojo.Provide;
import cn.smbms.service.provider.ProviderService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/Provide")
public class ProviderController {
    private Logger logger = Logger.getLogger(ProviderController.class);

    @Resource
    private ProviderService providerService;


    @RequestMapping(value = "/providerlist.html")
    public String getUserList(Model model,
                              @RequestParam(value = "queryProCode",required = false) String queryProCode,
                              @RequestParam(value = "queryProName",required = false) String queryProName,
                              @RequestParam(value = "pageIndex",required = false) String pageIndex){
        logger.info("provideList ---> queryUserName：" + queryProCode);
        logger.info("provideList ---> queryUserRole：" + queryProName);
        logger.info("provideList ---> pageIndex：" + pageIndex);
        List<Provide> provideList = null;
        //设置页码容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if (queryProCode == null) {
            queryProCode = "";
        }
        if (queryProName != null){
           queryProName = "";
        }
        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //总数量
        int totalCount = providerService.getProviderCount(queryProCode,queryProName);//============_queryProName

        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();



        if(currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        provideList = providerService.getProviderList(queryProCode,queryProName,pages.getCurrentPageNo(),pages.getPageSize());//============_queryProName

        model.addAttribute("providerList",provideList);
        model.addAttribute("queryProCode",queryProCode);
        model.addAttribute("queryProName",queryProName);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",currentPageNo);
        return "providerlist";
    }

    @RequestMapping(value = "/provideradd.html",method = RequestMethod.GET)
    public String addProvide(@ModelAttribute("provide") Provide provide){     //@ModelAttribute("provide") Provide provide
        return "provideradd";
    }

    //addProvideSave方法 ,保存新增供应商信息
  /* @RequestMapping(value = "/provideradd.html",method = RequestMethod.POST)
    public String addProvideSave(@Valid Provide provide, BindingResult bindingResult,HttpServletRequest request,
                                 @RequestParam(value = "attachs", required = false) MultipartFile[] attachs){
        //provide.setCreatedBy(((Provide)session.getAttribute(Constants.USER_SESSION)).getId());
        //provide.setCreationDate(new Date());
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("uploadFile path ============== > " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();  //原文件名
                logger.info("uploadFile oldFileName ============== > " + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);    //原文件后缀
                logger.debug("uploadFile prefix============> " + prefix);
                int filesize = 500000;
                logger.debug("uploadFile size============> " + attach.getSize());
                if (attach.getSize() > filesize) {
                    //上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";//1000000
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = path + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = path + File.separator + fileName;
                    }
                    logger.debug("idPicPath: " + idPicPath);
                    logger.debug("workPicPath: " + workPicPath);

                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            provide.setId(provide.getId());
            if (providerService.add(provide)) {
                return "redirect:/Provide/providerlist.html";
            }
       }
        return "/Provide/provideradd";
    }*/


    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String view(@PathVariable String id, Model model) {
        Provide provide = providerService.getProvideById(id);
        model.addAttribute(provide);
        return "/Provide/providerview";
    }

  @RequestMapping(value = "/modify.html/{id}", method = RequestMethod.GET)
    public String modify(@PathVariable String id, Model model) {
        Provide provide = providerService.getProvideById(id);
        model.addAttribute(provide);
        return "/Provide/providermodify";
    }

   @RequestMapping(value = "/provideradd.html", method = RequestMethod.POST)
    public String modifyProvider(Provide provide) {
        provide.setModifyBy(provide.getModifyBy() == null ? 1 : provide.getModifyBy() + 1);
        provide.setModifyDate(new Date());
        if (providerService.modify(provide)) {
            return "redirect:/Provide/providerlist.html";
        }
        return "/Provide/providermodify";
    }


}
